// SlagCar/OrderAdd/OrderAdd.js
let orderBehavior = require('./orderBehavior')
Page({
  behaviors: [ orderBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    /*mainField:[
      {field_id: 'xiangmumingchen',type: 'select',label: '项目',selectType: 'project',required: true},
      {field_id: 'delivery_name',type: 'select',label: '工地',selectType: 'delivery',required: true},
      {field_id: 'Order_client_Name',type: 'select',label: '所属单位',selectType: 'client',disabled: false},
      {label: '联系方式',children: [
          {field_id: 'gongdilianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'gongdilianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {label: '订单名称',field_id: 'order_name',type: 'text',placeholder: '订单名称',required: true},
      /!*{label: '工地价格',required: true,children: [
          {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
        ]},*!/
      {label: '开始时间',field_id: 'start_time',type: 'calendar',placeholder: '请选择',required: true},
      {label: '结束时间',field_id: 'end_time',type: 'calendar',placeholder: '请选择',required: true},
      {label: '需要运单号/挖机号',field_id: 'need_fill_order_no',type: 'radio',placeholder: '请选择',radioType: 'order'},
      {label: '需要运单/挖机图片',field_id: 'need_fill_order_img',type: 'radio',placeholder: '请选择',radioType: 'img'},
      // {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      // {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},
      {label: '需要填写趟次',field_id: 'need_fill_transport_times',type: 'radio',placeholder: '请选择',radioType: 'need_fill_transport_times'},
      {label: '需要填写方数',field_id: 'need_fill_square_number',type: 'radio',placeholder: '请选择',radioType: 'need_fill_square_number'},
      {label: '需要车数控制',field_id: 'need_car_no_control',type: 'radio',placeholder: '请选择',radioType: 'need_car_no_control'},
      {label: '填写车数',field_id: 'fill_car_no',type: 'number',placeholder: '请选择',radioType: 'need_car_no_control'},
    ], //订单主表字段
    destField:[
      {field_id: 'destination_name',type: 'select',label: '消纳场',selectType: 'destination',required: true},
      {field_id: 'Order_client_Name',type: 'select',label: '所属单位',selectType: 'destClient',disabled: false},
      {label: '联系方式',children: [
          {field_id: 'xiaonachanglianxiren',type: 'text',placeholder: '联系人'},
          {field_id: 'xiaonachanglianxidianhua',type: 'text',placeholder: '联系电话'},
        ]},
      {field_id: 'goods_name',type: 'select',label: '泥种',selectType: 'goods',required: true},
      {label: '工地价格',required: true,children: [
          {field_id: 'construction_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'construction_price',type: 'digit',placeholder: '工地价格'},
        ]},
      {label: '消纳场价格',required: true,children: [
          {field_id: 'destination_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'Order_amount',type: 'digit',placeholder: '消纳场价格'},
        ]},
      {label: '司机价格',required: true,children: [
          {field_id: 'driver_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'driver_price',type: 'digit',placeholder: '司机价格'},
        ]},
      {label: '额外金额',required: false,children: [
          {field_id: 'extra_payment',type: 'picker',placeholder: '请选择'},
          {field_id: 'extra_price',type: 'digit',placeholder: '额外金额'},
        ]},

      {label: '泥尾需要挖机号',field_id: 'need_fill_excavator_no_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_no_end'},
      {label: '泥尾需要挖机图片',field_id: 'need_fill_excavator_img_end',type: 'radio',placeholder: '请选择',radioType: 'need_fill_excavator_img_end'},

    ], //消纳场明细表字段*/

  /*  formData: {}, // 工地信息（主表）

    driverAssign: [], //指派人员列表（子表）
    //泥尾信息（二级明细表）
    destinationAssign: [
      {
        row_id: 0,
        destination_payment: '应付',
        driver_payment: '应付',
        extra_payment: '应付',
        is_used: true
      }
    ],    //泥尾（子表）*/

  /*  /!*弹出层显示标识*!/
    showDelivery: false,  //显示工地选择列表
    showDestination: false, //显示消纳场选择列表
    showGoods: false, //显示泥种选择列表
    showDriver: false,  //显示司机选择列表
    showClient: false,  //显示所属单位列表
    showDestClient: false,  //显示泥尾所属单位列表
    showProject: false,   //显示项目列表

    /!*弹出层显示内容*!/
    deliveryList: [], //工地列表
    destinationList: [], //消纳场列表
    goodsList: [],  //泥种列表
    driverList: [],   //司机列表
    clientList: [],  //所属单位列表
    destClientList: [], //泥尾所属单位列表
    projectList: [],  //项目列表

    /!*搜索*!/
    searchValue: {},  //搜索值变化集合

    /!*应收应付选择器*!/
    columns: ['应收','应付'],
    showPicker: false,
    curtPickerField: '',  //当前选择器字段id
    curtPickerIndex: 0, //当前选择器修改内容对应泥尾索引
    defaultPickerValue: '',

    /!*日历*!/
    showCalendar: false,
    defaultDatetimeValue: '',
    resetFlag: false,

  //  司机分级选择
    firstActiveIndex: 0,
    secondActiveIndex: 0,
    activeId: [],
    items: [],
    checkAll: false,

    // 231218 yan 车队选择修改为弹出选择器选择
    showDriverPicker: false, //司机车队选择器显示
    carTeamColumns: [
      {values:[],defColumns: 0,}, //一级车队
      {values: [],defColumns: 0,} //二级车队
    ],  //车队选择器选项
    crtDriver: [],  //过滤车队显示的司机
    driverPickerValue: [],  //选择器选择的值

    // 231218 end
*/
  },

  bindSubmit(){
    let {formData,destinationAssign,driverAssign,driverDetail} = this.data,
      obj = {
        xiangmu: '请选择项目',
        reference1_all_delivery: '请选择工地',
        Order_client_ID: '',  //工地所属单位
        gongdilianxiren: '',
        gongdilianxidianhua: '',
        order_name: '请输入订单名称',
        start_time: '请选择开始时间',
        end_time: '请选择结束时间',
        need_fill_order_no: '',
        need_fill_order_img: '',
        need_fill_excavator_no: '',
        need_fill_excavator_img: '',
        need_fill_transport_times: '',
        need_fill_square_number: '',
        need_car_no_control: '',
        fill_car_no: '',
        is_used: ''
      },
      obj2 = {
        reference1_all_destination: '请选择消纳场',
        Order_client_ID: '',  //消纳场所属单位
        xiaonachanglianxiren: '',
        xiaonachanglianxidianhua: '',
        reference1_goods: '请选择泥种',
        construction_payment: '',
        construction_price: '请输入工地价格',
        destination_payment: '',
        Order_amount: '请输入消纳场价格',
        driver_payment: '',
        driver_price: '请输入司机价格',
        extra_payment: '',
        extra_price: '',    //额外价格
        need_fill_excavator_no_end: '',
        need_fill_excavator_img_end: '',
        need_fill_order_no_end: '',
        need_fill_order_img_end: '',
        is_used: ''
      },
      destDetail = [],driDetail = [];
    let mainData = this.getSubmitData(formData,obj);
    if (!mainData) return;
    if (mainData.need_car_no_control && !Number(mainData.fill_car_no)) {
      wx.$toast('请输入车数');
      return
    }
    if (!destinationAssign.length) {
      wx.$toast('请添加泥尾');
      return
    }

    let destFlag = true;
    destinationAssign.forEach(item => {
      let destData = destFlag && this.getSubmitData(item,obj2);
      if (!destData) {
        destFlag = false;
        return
      }
      let details = this.fmtDestDriverDetl(item.details) || []
      destDetail.push({
        details: [{
          table_id: 'muck_order_assign_destination_personnel',
          entitys: details
        }],
        entity: destData
      });

    });
    driverDetail.forEach(item =>{
      driDetail.push({
        details: [],
        entity: item
      })
    })

    if (!destFlag) return;

    let details = [
      {
        table_id: 'muck_order_assign_destination',
        entitys: destDetail
      },
      {
        table_id: 'muck_order_assign_personnel',
        entitys:driDetail
      }
    ];

    let post = {
      table: {
        table_id: 'muck_order_main',
        entitys: [
          {
            details,
            entity: mainData
          }
        ]
      }
    };
    console.log(post);
    // return;
    wx.showLoading({mask: true})
    let url = 'DynamicUpdate/dynamic_update_v3';
    wx.$post(3,url,post).then(res => {
      if (res.errcode != 0) return;
      wx.$toast('提交成功');
      let row = res.data.row[0],
        entity = row && row.entity[0],
        row_id = entity && entity.row_id || 0;
      if (row_id){
        wx.redirectTo({url:'/SlagCar/OrderDetail/OrderDetail?row_id='+ row_id});
      } else {
        wx.reLaunch();
      }

    })
  },

  prepare(){
    // 250327 yan 注释 初始不加载，点击选择时加载
    /*this.getProject();
    this.getDelivery();
    this.getDestination();
    this.getGoods();
    this.getClient();
    this.getDestClient();
    this.getDriver();
    this.setDriverLevel(1);*/
    //设置初始默认值
    this.getCustomField('muck_order_main').then(res =>{
      let formData = {
        row_id: 0,
        // construction_payment: '应收',
        need_fill_order_no: true,
        need_fill_order_img: true,
        need_fill_excavator_no: true,
        need_fill_excavator_img: true,
        need_fill_transport_times: true,
        need_fill_square_number: true,
        need_car_no_control: true,
        // need_fill_excavator_no_end: true,
        // need_fill_excavator_img_end: true,
        is_used: true
      },
        fieldArr = ['need_fill_order_no','need_fill_order_img','need_fill_excavator_no','need_fill_excavator_img','need_fill_transport_times'
        ,'need_fill_square_number','need_car_no_control'];
      res.forEach(item =>{
        let {field_id,option,defaultValue,type} = item;
        if (fieldArr.includes(field_id)) {
          if (type === 'bit')formData[field_id] = !!defaultValue;
         /* if (field_id === 'construction_payment'){
            let opts = option && JSON.parse(option),
              def = opts && opts.find(ite => ite.isDefault);
            formData[field_id] = def && def.label || '应收'
          }*/
        }
      });
      this.setData({formData})
    });
    this.getCustomField('muck_order_assign_destination').then(res => {
      let destinationDefData = {
        row_id: 0,
        construction_payment: '应收',
        destination_payment: '应付',
        driver_payment: '应付',
        extra_payment: '应付',
        is_used: true
      },
        fieldArr = ['construction_payment','destination_payment','driver_payment','extra_payment','need_fill_excavator_no_end','need_fill_excavator_img_end','need_fill_order_no_end','need_fill_order_img_end'];

      res.forEach(item => {
        let {field_id,option,defaultValue,type} = item;
        if (fieldArr.includes(field_id)) {
          if (type === 'bit')destinationDefData[field_id] = !!defaultValue;
          else {
            let opts = option && JSON.parse(option),
              def = opts && opts.find(ite => ite.isDefault);
            destinationDefData[field_id] = def && def.label || '应付';
          }
        }
      });
      this.setData({
        destinationDefData,
        [`destinationAssign[0]`]: {...destinationDefData}
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAuthorityList('muck_order_main').then(res=>{
      this.setData({
        auth: res,
      });
      this.initField();
      this.prepare();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
